package com.rd.p2p.app.bond;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.BondProtocolService;
import com.qdlc.p2p.biz.service.BondService;
import com.qdlc.p2p.biz.service.BondTenderService;
import com.qdlc.p2p.biz.service.BorrowCollectionService;
import com.qdlc.p2p.biz.service.BorrowRepaymentService;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.BorrowUploadService;
import com.qdlc.p2p.biz.service.UserBaseInfoService;
import com.qdlc.p2p.biz.service.UserCertificationApplyService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserRedEnvelopeService;
import com.qdlc.p2p.biz.service.VerifyLogService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.PropertiesUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.checkrule.BondConfigRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.Bond;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.BorrowUpload;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserBaseInfo;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.BondModel;
import com.qdlc.p2p.dal.model.BondTenderModel;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.UserBaseInfoModel;
import com.qdlc.p2p.dal.model.UserCertificationApplyModel;
import com.qdlc.p2p.dal.model.UserIdentifyModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 债权action
 * @author zhangyz
 */
public class AppBondAction extends BaseAction<BondModel> implements ModelDriven<BondModel> {
	
	private static Logger logger = Logger.getLogger(AppBondAction.class);
	
	@Resource
	private BondService bondService;
	@Resource
	private BondTenderService bondTenderService;
	@Resource
	private BorrowService borrowService;
	@Resource
	private UserBaseInfoService userBaseInfoService;
	@Resource
	private UserIdentifyService userIdentifyService;
	@Resource
	private AccountService accountService;
	@Resource
	private BorrowUploadService borrowUploadService;
	@Resource
	private UserCertificationApplyService userCertificationApplyService;
	@Resource
	private VerifyLogService verifyLogService;
	@Resource
	private BorrowRepaymentService borrowRepaymentService;
	@Resource
	private BondProtocolService bondProtocolService;
	@Resource
	private BorrowCollectionService borrowCollectionService;
	@Resource
	private UserRedEnvelopeService userRedEnvelopeService;
	
	private User user;
	
	private Map<String, Object> data;
	
	

	/**
	 * 可转让债权列表（输出json字符串）
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/useBondList")
	public void saleableBondList() throws Exception {
		
		data = new HashMap<String, Object>();
		// 债权发布者
		user = getSessionUser();
		model.setUser(user);
		PageDataList<BondModel> list = bondService.getBondModelPage(model);
		data.put("data", list);
		
    	//债权规则
    	BondConfigRuleCheck bondConfigRuleCheck = RuleCheckHelper.getValue(BondConfigRuleCheck.class);
    	data.put("bondAprL", bondConfigRuleCheck.bondAprL);
    	data.put("bondAprH", bondConfigRuleCheck.bondAprH);
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 转让专区债权列表（输出json字符串）
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/bondList")
	public void bondList() throws Exception {
		
		data = new HashMap<String, Object>();
		PageDataList<BondModel> list = bondService.getBondList(model);
		List<BondModel> allList = list.getList();
		if("1".equals(paramString("limitListFlag")) && allList != null && allList.size() > 4){
			List<BondModel> limitList = new ArrayList<BondModel>();
			for (int i = 0; i < 4; i++) {
				limitList.add(allList.get(i));
			}
			list.setList(limitList);
		}
		data.put("data", list);
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}	
	
	/**
	 * 发布债权
	 * @throws Exception if has error
	 */
	@Action(value="/bond/addBond")
	public void addBond() throws Exception {

		// 债权发布者
		user = getSessionUser();
		model.setUser(user);
		// 标信息
		Borrow borrow = borrowService.getBorrowById(model.getBorrowId());
		model.setBorrow(borrow);
		// 发布债权前校验
		model.checkBeforAddBond(model);
		// 债权信息
		Bond bond = model.prototype();
		bondService.addBond(bond);
		
		data = new HashMap<String,Object>();
		data.put("resCode", "1");
		data.put("resMsg",PropertiesUtil.getValue("AppBond01"));
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 转让中债权列表（输出json字符串）
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/sellingBondList")
	public void sellingBondList() throws Exception {
		
		data = new HashMap<String, Object>();
		// 债权发布者
		user = getSessionUser();
		model.setUser(user);
		PageDataList<BondModel> list = bondService.getSellingBondList(model);
		data.put("data", list);
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 已转出债权列表（输出json字符串）
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/soldBondList")
	public void soldBondList() throws Exception {
		
		data = new HashMap<String, Object>();
		// 债权发布者
		user = getSessionUser();
		model.setUser(user);
		PageDataList<BondModel> list = bondService.getSoldBondList(model);
		data.put("data", list);
		data.put("resMsg", "1");
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 已转入债权列表（输出json字符串）
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/boughtBondList")
	public void boughtBondList() throws Exception {
		
		data = new HashMap<String, Object>();
		// 债权发布者
		user = getSessionUser();
		model.setUser(user);
		PageDataList<BondTenderModel> list = bondTenderService.getBoughtBondList(model);
		data.put("data", list);
		data.put("resMsg", "1");
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * 债权详情页面收益
	 * @throws Exception
	 */
	@Action(value="/app/user/detailInterest")
	public void detailInterest()throws Exception{
		data = model.validParams();
		if(StringUtil.isBlank(data)){
			Map<String, Object> data = new HashMap<String, Object>();
			Bond bond = bondService.find(model.getUuid());
			Object[] obj  = borrowCollectionService.getBorrowCollectionList(bond.getBorrowTenderId());
			if(obj != null && obj.length == 2){
				double percent = BigDecimalUtil.div(model.getMoney(), Double.parseDouble(obj[0].toString()));
				double interest = BigDecimalUtil.mul(Double.parseDouble(obj[1].toString()),percent);
				data.put("interest", interest);
			}else{
				data.put("interest", 0);
			}
			data.put("resCode", "1");
			printJson(getStringOfJpaObj(data));
		}else{
			printWebJson(getStringOfJpaObj(data));
		}
	}
	
	
	/**
	 * 债权详情JSON数据
	 * @throws Exception
	 */
	@Action("/app/user/bondDetail")
	public void bondDetail() throws Exception {
		/*this.saveToken("bondTenderToken");
		String bondTenderToken = (String) session.get("bondTenderToken");*/
		
		user = getSessionUser();
		
		data = new HashMap<String, Object>();

		/*data.put("bondTenderToken", bondTenderToken);*/
		
		// 债权信息
		BondModel bond = bondService.getBondDetail(model);
		data.put("bond", bond);
		
		// 标信息
		long borrowId = bond.getBorrowId();
		Borrow borrow = borrowService.find(borrowId);
		User borrowUser = borrow.getUser();

		
		// 借款人信息
		UserBaseInfo userBaseInfo = userBaseInfoService.findByUserId(borrowUser.getUserId());
		if(userBaseInfo != null){
			UserBaseInfoModel userBaseInfoModel = UserBaseInfoModel.instance(userBaseInfo);
			userBaseInfoModel.setUser(null); //防止前台查看用户信息
			data.put("userBaseInfo", userBaseInfoModel);
		}
		
		// 资料审核状态
		List<UserCertificationApplyModel> certificationApply = userCertificationApplyService.findByUser(borrowUser);
		data.put("certificationApply", certificationApply);
		
		// 借款资料
		List<BorrowUpload> borrowUploads = borrowUploadService.findByBorrowId(borrowId);
		data.put("borrowUploads", borrowUploads);
		
		String username = borrowUser.getUserName();
		String hideName = username.charAt(0)+"******"+username.charAt(username.length()-1);
		
		BorrowModel borrowModel = BorrowModel.instance(borrow);
		borrowModel.setUserName(hideName);
		borrowModel.setUser(null);
		data.put("borrow", borrowModel);

		if (user != null) {
			UserIdentify userIdentify = userIdentifyService.findByUserId(getSessionUserId());
			UserIdentifyModel userIdentifyModel = UserIdentifyModel.instance(userIdentify);
			String uName = user.getUserName();
			userIdentifyModel.setUserName(uName.charAt(0)+"******"+uName.charAt(uName.length()-1));
			userIdentifyModel.setUser(null);
			data.put("userInvestIdentify", userIdentifyModel);
			data.put("payPwd", StringUtil.isBlank(user.getPayPwd()));
			
			if ("".equals(paramString("borrowPreview"))) {
				UserCache userCache = UserUtils.getUserCacheByUserId(user.getUserId());
				data.put("userType",userCache.getUserType());
				Account account = accountService.findAccountByUserId(user.getUserId());
				AccountModel accountModel = AccountModel.instance(account);
				accountModel.setUser(null);
				data.put("account", accountModel);
			}
		}
		
		// 债权转让记录
		BondTenderModel bondTenderModel = new BondTenderModel();
		bondTenderModel.setBondId(model.getId());
		bondTenderModel.setUuid(model.getUuid());
		PageDataList<BondTenderModel> bondTenderList = bondTenderService.getTenderModelPage(bondTenderModel);
		data.put("bondTenderList", bondTenderList);
		data.put("url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.IMAGE_SERVER_URL));
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}
	
	
	/**
	 * 债权转让记录列表
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/latestTenerList")
	public void latestTenerList() throws Exception {
		data = new HashMap<String, Object>();
		// 最新债权转让成交记录
		data.put("latestTenerList", bondTenderService.getLatestTenerList());
		data.put("serverTime", DateUtil.getNow());
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 债权转让记录列表
	 * 
	 * @throws Exception if has error
	 */
	@Action(value="/app/user/bondTenderList")
	public void bondTenderList() throws Exception {
		
		data = new HashMap<String, Object>();
		BondTenderModel bondTenderModel = new BondTenderModel();
		bondTenderModel.setBondId(model.getId());
		bondTenderModel.setUuid(model.getUuid());
		bondTenderModel.setPage(model.getPage());
		PageDataList<BondTenderModel> bondTenderList = bondTenderService.getTenderModelPage(bondTenderModel);
		data.put("data", bondTenderList);
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}	
}
